package com.cancer.common.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.cancer.common.web.Sort.Direction;
import com.cancer.common.web.Sort.Order;


/**
 * 分页拦截器，将分页参数取出注入到PagingContext中
 * 
 * @Company GeekPlus
 * @Project beetle
 * @since 1.0.0
 * @Author 刘俊
 * @Date 2016年4月13日 下午4:34:04
 * @Description
 * 
 */
public class PagingFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		// do nothing
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
		if (true) {
			System.err.println(uri);
		}

		// 参数获取
		try {
			int currentPage = ObjectsUtil.parseInt(req.getParameter("currentPage"), 1);
			int pageSize = ObjectsUtil.parseInt(req.getParameter("pageSize"), 15);
			String[] orders = req.getParameterValues("order");
			String[] directions = req.getParameterValues("direction");
			// 采用页码和页大小分页
			PagingContext.setNoAndSize(currentPage, pageSize);

			/*
			 * 排序：只接受以下两种情况的传值，如传值错误则不进行排序
			 * 	1. 只写排序字段，则默认以升序ASC处理
			 * 		如：order=username&order=email
			 * 	2. 排序字段和排序方向一一对应
			 * 		如：order=username&direction=ASC&order=email&direction=DESC 
			 */
			Direction dd = null;
			if (directions == null || directions.length == 0) {
				dd = Direction.ASC;
			}
			if (orders != null && (dd != null || orders.length == directions.length)) {
				// orders && directions不为空，且长度相等时才成立
				for (int i = 0; i < orders.length; ++i) {
					// 
					Direction direction = dd == null ? Direction.fromString(directions[i]) : dd;
					PagingContext.addSortItem(new Order(direction, orders[i]));
				}
			}

			// 继续执行filter chain
			chain.doFilter(request, response);
		} finally {
			PagingContext.removeAll();
		}
	}

	@Override
	public void destroy() {

		// do nothing
	}

}
